﻿@using Microsoft.EntityFrameworkCore
@using Radzen
@using System.Text.Json
@inject DialogService DialogService
@inject ProductService ProductService

<RadzenTemplateForm TItem="cts_ProductType" EditContext="editContext" Data="@model" InvalidSubmit=@OnInvalidSubmit Submit=@OnSubmit>
    <DataAnnotationsValidator />
    <ValidationSummary />
    <RadzenStack Gap="1rem">
        <RadzenStack class="rz-p-0" Orientation="Orientation.Vertical" AlignItems="AlignItems.Normal" JustifyContent="JustifyContent.SpaceBetween">
            <RadzenRow Gap="1rem">
                <RadzenColumn Size="12" SizeMD="12">
                    <RadzenStack>
                        <RadzenFormField Text="名称" Style="width: 100%;">
                            <ChildContent>
                                <RadzenTextBox @bind-Value="model!.Name" />
                            </ChildContent>
                            <Helper>
                                <RadzenText TextStyle="TextStyle.Caption" Style="color:red">* 必填</RadzenText>
                            </Helper>
                        </RadzenFormField>
                    </RadzenStack>
                </RadzenColumn>
            </RadzenRow>

            <RadzenRow Gap="1rem">
                <RadzenColumn Size="12" SizeMD="12">
                    <RadzenStack>
                        <RadzenFormField Text="上级分类" Style="width: 100%; height: 100px">
                            <ChildContent>
                                <RadzenTree Style="width: 100%; height: 100px" @bind-Value=@SelectedNode Data=@Tree Change="@OnTreeChange">
                                    <RadzenTreeLevel TextProperty="Name" 
                                    ChildrenProperty="Children" 
                                    Expanded=@ShouldExpand
                                    HasChildren=@(e => (e as TreeProductTypeDto)!.Children.Any()) />
                                </RadzenTree>
                            </ChildContent>
                        </RadzenFormField>
                    </RadzenStack>
                </RadzenColumn>
            </RadzenRow>

            <RadzenRow Gap="1rem">
                <RadzenColumn Size="12" SizeMD="12">
                    <RadzenStack>
                        <RadzenFormField Text="排序" Style="width: 100%;">
                            <ChildContent>
                                <RadzenNumeric @bind-Value="model!.Sort" />
                            </ChildContent>
                        </RadzenFormField>
                    </RadzenStack>
                </RadzenColumn>
            </RadzenRow>
        </RadzenStack>

        <RadzenStack Gap="1rem" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.End" Style="height: 20%;">
            <RadzenButton ButtonType="ButtonType.Button" ButtonStyle="ButtonStyle.Secondary" Text="取消" Click="OnCancel"/>
            <RadzenButton ButtonType="ButtonType.Submit" ButtonStyle="ButtonStyle.Primary" Text="保存" />
        </RadzenStack>
    </RadzenStack>
</RadzenTemplateForm>

@code {
    [Parameter]
    public cts_ProductType? PProductType { get; set; }
    private EditContext? editContext;
    private cts_ProductType? model { get; set; }
    List<TreeProductTypeDto>? Tree { get; set; }
    object? SelectedNode;

    bool ShouldExpand(object data)
    {
        return true;
    }

    async void OnSubmit(cts_ProductType model)
    {
        if (model == null)
        {
            return;
        }

        // 处理选中的节点
        if (SelectedNode != null)
        {
            model.ParentId = ((TreeProductTypeDto)SelectedNode).Id;
        }
        else
        {
            await DialogService.Alert("未选择父节点", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        }
        
        try
        {
            var result = ProductService.SaveProductType(model);
            DialogService.Close(result);
        }
        catch (Exception e)
        {            
            await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
        }
    }

    private void OnTreeChange(object value)
    {
        var x = value as Radzen.TreeEventArgs;
        SelectedNode = (TreeProductTypeDto)x.Value;
    }

    private TreeProductTypeDto FindNodeById(List<TreeProductTypeDto> nodes, long id)
    {
        foreach (var node in nodes)
        {
            if (node.Id == id)
            {
                return node;
            }

            var found = FindNodeById(node.Children, id);
            if (found != null)
            {
                return found;
            }
        }

        return null;
    }
    void OnInvalidSubmit(FormInvalidSubmitEventArgs args)
    {
        var errors = new Dictionary<string, List<string>>();
    }

    protected override void OnInitialized()
    {
        model = PProductType;
        editContext = new EditContext(model!);
        Tree = ProductService.GetTreeProductType();

        // 选中节点
        if (model != null)
        {
            SelectedNode = FindNodeById(Tree, model.ParentId);
        }
        else
        {
            SelectedNode = Tree.FirstOrDefault();
        }
    }

    private void OnCancel()
    {
        DialogService.Close(null);
    }    

}

